import { AxiosError, AxiosRequestConfig, AxiosResponse } from "axios";
import { ref, shallowRef } from "vue";
import $http from "@/api/http";

function useAxios<T = any>(url: string, config?: AxiosRequestConfig) {
  const response = shallowRef<AxiosResponse<T>>();
  const data = shallowRef<T>();
  const isFinished = ref(false);
  const isLoading = ref(true);
  const error = shallowRef<AxiosError<T>>();
  $http(url, config)
    .then(res => {
      response.value = res;
      data.value = res.data;
    })
    .catch(err => {
      error.value = err;
    })
    .finally(() => {
      isLoading.value = false;
      isFinished.value = true;
    });
  return {
    response,
    data,
    error,
    finished: isFinished,
    loading: isLoading
  };
}

export default useAxios;
